package com.cynen.crawler;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * httpPost请求方式测试.
 */

public class HttpPostTest {
    public static void main(String[] args) {
        // 基本使用步骤.

        // 1.创建对象.
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 2.创建get请求对象.
        HttpPost httpPost = new HttpPost("http://www.itcast.cn");

        CloseableHttpResponse httpResponse = null;
        try {
            // 3.使用httpclient发起请求.
            httpResponse = httpClient.execute(httpPost);
            // 4.解析响应.
            if (httpResponse.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(httpResponse.getEntity(),"utf8");
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            // 5.关闭资源.
            try {
                // 关闭响应链接
                httpResponse.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            try {
                // 关闭客户端.
                httpClient.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}
